package com.example.springsecurity01.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author lzh
 * @date 2019/9/16 - 14:46
 */
@Controller
public class HomeController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }




    /**
     * 获取登录信息的方式
     *
     *        主要是通过SecurityContextHolder获取到上下文SecurityContext，
     *        通过SecurityContext获取到权限信息Authentication，最后通过Authentication获取到当前的登录信息
     * @param model
     * @return
     */
    @GetMapping({"","/","/index"})
    public String index(Model model) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal)) {
            model.addAttribute("name","anonymous");
        }else {
            User user = (User)principal;
            model.addAttribute("name",user.getUsername());
        }
        return "index";
    }

}
